package com.eqdd.yiqidian.ui.yiqiyue;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.eqdd.yiqidian.AddArticleActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ArticleMenuListBean;
import com.eqdd.yiqidian.bean.rebuild.YueArticleBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.select.SelectTextMultiActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ListUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.SplitUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.eqdd.yiqidian.widget.FlowLayoutManager;
import com.gamerole.richtextview.RichEditor;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import io.reactivex.Flowable;

import static android.view.View.VISIBLE;

/**
 * @author吕志豪 .
 * @date 17-12-6  下午2:42.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class AddArticleActivity extends BaseActivity implements ColorChooserDialog.ColorCallback {

    private static final int MAX_NUM = 3;
    private AddArticleActivityCustom dataBinding;
    private RichEditor mEditor;
    private ArticleMenuListBean articleMenu;
    private SlimAdapterEx slimAdapterEx;
    private List<String> stringList;
    private String imgUrl;
    private String msg;
    private String textContent;
    private EditDialogFragment editDialog;
    private int id;
    private YueArticleBean yueArticleBean;
    private List<ArticleMenuListBean> menuItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_article);
        initTopTitleBar(VISIBLE, "写文章↓");
        id = getIntent().getIntExtra(Config.ID, 0);
        initTopRightText(id == 0 ? "发布" : "更新", v -> {
            if (checkParam()) {
                dataBinding.editor.getText(s -> {
                    textContent = s.length() > 60 ? s.substring(0, 60) : s;
                    imgUrl = getImgUrl(dataBinding.editor.getHtml());
                    String lable = SplitUtil.combin(stringList, ",") == null ? " " : SplitUtil.combin(stringList, ",");
                    if (id == 0) {
                        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.YUE_ADD_ARTICLE)
                                .params("menuId", articleMenu.getId())
                                .params("userGuid", user.getGuid())
                                .params("title", dataBinding.etTitle.getText().toString().trim())
                                .params("content", dataBinding.editor.getHtml())
                                .params("homeImage", TextUtils.isEmpty(imgUrl) ? " " : imgUrl)
                                .params("label", lable)
                                .params("source", 0)
                                .params("companyId", 0)
                                .params("textContent", TextUtils.isEmpty(textContent) ? " " : textContent)
                                .execute(new DialogCallBack<HttpResult>(AddArticleActivity.this) {
                                    @Override
                                    public void onSuccess(Response<HttpResult> response) {
                                        HttpResult httpResult = response.body();
                                        ToastUtil.showShort(httpResult.getMsg());
                                        if (httpResult.getStatus() == 200) {
                                            GreenDaoUtil.deleteDraft(id);
                                            setResult(Config.SUCCESS);
                                            finish();
                                        }
                                    }
                                });
                    } else {
                        updateDraft();
                    }
                });

            } else {
                ToastUtil.showShort(msg);
            }
        });
    }

    private String getImgUrl(String html) {
        // 按指定模式在字符串查找
        String pattern = "<img[\\S\\s]*?\"([\\s\\S]*?)\"[\\S\\s]*?>";

        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(html);
        if (m.find()) {
            if (m.groupCount() > 0) {
                String url = m.group(1);
                return URI.create(url).getPath();
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    private boolean checkParam() {
        if (TextUtils.isEmpty(dataBinding.etTitle.getText())) {
            msg = "请输入标题";
            return false;
        }
        if (TextUtils.isEmpty(dataBinding.editor.getHtml())) {
            msg = "请输入内容";
            return false;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if (articleMenu == null) {
            finish();
        } else {
            if (id == 0) {
                saveDraft();
                super.onBackPressed();
            } else {
                updateDraft();
            }
        }
    }

    private void updateDraft() {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.YUE_UPDATE_ARTICLE)
                .params("articleId", id)
                .params("userGuid", AppConstent.user.getGuid())
                .params("articleTitle", dataBinding.etTitle.getText().toString())
                .params("articleContent", mEditor.getHtml())
                .params("textContent", textContent)
                .execute(new DialogCallBack<HttpResult>(AddArticleActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            GreenDaoUtil.deleteDraft(id);
                            setResult(Config.UPDATE);
                            AddArticleActivity.super.onBackPressed();
                        }
                    }
                });
    }

    @Override
    public void initData() {
        dataBinding.recyclerView.setLayoutManager(new FlowLayoutManager());
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_74, new SlimInjector<String>() {
            @Override
            public void onInject(String data, IViewInjector injector) {
                injector.text(R.id.tv_content, data);
            }
        })
                .register(R.layout.list_item_76, new SlimInjector<Integer>() {
                    @Override
                    public void onInject(Integer data, IViewInjector injector) {

                    }
                }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        slimAdapterEx.getData().add(1);
        slimAdapterEx.notifyItemInserted(0);
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    if (slimAdapterEx.getDataItem(position) instanceof Integer) {
                        Bundle bundle = new Bundle();
                        bundle.putInt(Config.MAX_NUM, MAX_NUM);
                        bundle.putInt(Config.OPTION, 44);
                        bundle.putInt(Config.DEEP, 1);
                        startActivityForResult(SelectTextMultiActivity.class, bundle, Config.SELECT_MULTI_TEXT);
                    } else {
                        slimAdapterEx.getData().remove(position);
                        slimAdapterEx.notifyItemRemoved(position);
                        if (slimAdapterEx.getData().size() == MAX_NUM - 1) {
                            slimAdapterEx.getData().add(1);
                        }
                    }
                });
    }

    @Override
    public void setView() {
        mEditor = findViewById(R.id.editor);
        mEditor.setEditorHeight(200);
        mEditor.setEditorFontSize(22);
        mEditor.setEditorFontColor(Color.BLACK);
        mEditor.setPadding(10, 10, 10, 10);
        mEditor.setPlaceholder("内容");
        findViewById(R.id.action_bold).setOnClickListener(v -> mEditor.setBold());

        findViewById(R.id.action_italic).setOnClickListener(v -> mEditor.setItalic());


        findViewById(R.id.action_heading1).setOnClickListener(v -> mEditor.setHeading(1));

        findViewById(R.id.action_heading2).setOnClickListener(v -> mEditor.setHeading(2));

        findViewById(R.id.action_heading3).setOnClickListener(v -> mEditor.setHeading(3));

        findViewById(R.id.action_heading4).setOnClickListener(v -> mEditor.setHeading(4));
        findViewById(R.id.action_insert_line).setOnClickListener(v -> mEditor.insertHtml("<p style=\"border-top :1px solid #d9d9d9; padding: 20px 10px 0px 10px \"></p >"));

        findViewById(R.id.action_txt_color).setOnClickListener(v -> new ColorChooserDialog.Builder(AddArticleActivity.this, R.string.app_name)
                .allowUserColorInput(false)
                .customButton(R.string.md_custom_label)
                .presetsButton(R.string.md_presets_label)
                .show(getSupportFragmentManager()));


        findViewById(R.id.action_insert_image).setOnClickListener(v -> {
            PicUtil.single(AddArticleActivity.this, true);
        });

        findViewById(R.id.action_insert_link).setOnClickListener(v -> {
            showLinkDialog();
        });
        getFirstMenu();
    }

    private void initViewByBean(YueArticleBean yueArticleBean) {
        this.yueArticleBean = yueArticleBean;
        Flowable.fromIterable(menuItems)
                .filter(articleMenuListBean -> articleMenuListBean.getId() == yueArticleBean.getMenuId())
                .subscribe(articleMenuListBean -> articleMenu = articleMenuListBean);
        dataBinding.includeTitle.tvTitle.setText(articleMenu.getArticleName());
        dataBinding.etTitle.setText(yueArticleBean.getTitle());
        mEditor.setHtml(yueArticleBean.getContent());
        stringList = new ArrayList<>();
        for (String s : yueArticleBean.getLabel().split(",")) {
            if (!TextUtils.isEmpty(s)) {
                stringList.add(s);
            }
        }
        updateLabel();
    }

    private void showLinkDialog() {
        editDialog = ChooseAlertView.getEditDiglog("添加链接", "请输入文字", "请输入链接地址", (content) -> {
            if (TextUtils.isEmpty(content.get(0)) || TextUtils.isEmpty(content.get(1))) {
                ToastUtil.showLong("信息不完整，添加失败");
                return;
            } else {
                Pattern compile = Pattern.compile("^http(|s)://");
                Matcher matcher = compile.matcher(content.get(1));
                if (matcher.find()) {
                    mEditor.insertLink(content.get(1), content.get(0));
                } else {
                    mEditor.insertLink("http://" + content.get(1), content.get(0));
                }

            }
        });
        editDialog.show(getSupportFragmentManager(), "edit");
    }

    private void getFirstMenu() {
        OkGo.<HttpResult<List<ArticleMenuListBean>>>post(HttpConfig.BASE_URL + HttpConfig.YUE_ARTICLE_MENU)
                .params("userGuid", AppConstent.user.getGuid())
                .execute(new DialogCallBack<HttpResult<List<ArticleMenuListBean>>>(AddArticleActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<ArticleMenuListBean>>> response) {
                        HttpResult<List<ArticleMenuListBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            menuItems = httpResult.getItems();
                            if (ListUtil.isEmpty(menuItems)) {
                                showInput();
                            } else {
                                YueArticleBean draft = GreenDaoUtil.getDraft(id);
                                if (draft != null) {
                                    initViewByBean(draft);
                                } else if (id == 0) {
                                    articleMenu = menuItems.get(0);
                                    dataBinding.includeTitle.tvTitle.setText(articleMenu.getArticleName());
                                } else {
                                    OkGo.<HttpResult<YueArticleBean>>post(HttpConfig.BASE_URL + HttpConfig.YUE_ARTICLE_INFO)
                                            .params("articleId", id)
                                            .params("userGuid", AppConstent.user.getGuid())
                                            .execute(new DialogCallBack<HttpResult<YueArticleBean>>(AddArticleActivity.this) {
                                                @Override
                                                public void onSuccess(Response<HttpResult<YueArticleBean>> response) {
                                                    HttpResult<YueArticleBean> httpResult = response.body();
                                                    if (httpResult.getStatus() == 200) {
                                                        initViewByBean(httpResult.getItems());
                                                    }
                                                }
                                            });
                                }
                            }
                        }
                    }
                });
    }

    private void showInput() {
        new MaterialDialog.Builder(this)
                .title("新建文集")
                .positiveText("创建")
                .titleColor(getResources().getColor(R.color.red7))
                .canceledOnTouchOutside(false)
                .inputType(InputType.TYPE_CLASS_TEXT)//可以输入的类型-电话号码
                //前2个一个是hint一个是预输入的文字
                .input("文集名", "", (dialog, input) -> {
                    if (dialog.getInputEditText().length() > 0) {
                        dialog.getActionButton(DialogAction.POSITIVE).setEnabled(true);
                    } else {
                        dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);
                    }
                })
                .onPositive((dialog, which) ->
                        HttpUtil.addArticleMenu(AddArticleActivity.this,
                                dialog.getInputEditText().getText().toString().trim(),
                                () -> getFirstMenu()))
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.SELECT_MULTI_TEXT && resultCode == Config.SUCCESS) {
            stringList = data.getStringArrayListExtra(Config.STRING_LIST);
            updateLabel();
        }
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            HttpUtil.upLoadPic(AddArticleActivity.this, localMedias.get(0).getCompressPath(), url -> {
                mEditor.insertImage(url, "图片", 100);
            });
        }
    }

    private void updateLabel() {
        ArrayList temp = new ArrayList();
        temp.addAll(stringList);
        slimAdapterEx.updateData(temp);
        if (temp.size() < 5) {
            slimAdapterEx.getData().add(1);
            slimAdapterEx.notifyItemInserted(slimAdapterEx.getData().size() - 1);
        }
    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, int selectedColor) {
        mEditor.setTextColor(selectedColor);
    }

    @Override
    public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (id == 0 && articleMenu != null) {
            if (id == 0) {
                saveDraft();
            } else {
                saveArticle();
            }
        }
    }

    private void saveArticle() {
        yueArticleBean.setContent(mEditor.getHtml());
        yueArticleBean.setTitle(dataBinding.etTitle.getText().toString());
        yueArticleBean.setLabel(SplitUtil.combin(stringList, ",") == null ? "" : SplitUtil.combin(stringList, ","));
        yueArticleBean.setMenuId(articleMenu.getId());
        GreenDaoUtil.saveDraft(yueArticleBean);
    }

    private void saveDraft() {
        if (id == 0) {
            GreenDaoUtil.saveDraft(new YueArticleBean(0L,
                    dataBinding.etTitle.getText().toString(),
                    mEditor.getHtml(),
                    SplitUtil.combin(stringList, ",") == null ? "" : SplitUtil.combin(stringList, ","),
                    articleMenu.getId()));
        }
    }
}
